// pages/operation-center/add-contract/index.js
const app = getApp()
Page({
  data: {
    expand: false,
    permissionInfo: {
    },
    action: 'add',
    title: '添加权限组',
    userList: [],
    basePermissionList: [],
  },
  onLoad(option) {
    this.getUserList(option.id)
    if (option.id) {
      this.setData({
        title: '编辑权限组',
        action: 'edit'
      })
    }
  },
  getUserList(id) {
    app.axios('user', {
      op: 'ajaxUserDlList'
    }).then(res => {
      if (res.code) {
        this.setData({
          userList: res.lists
        })
        this.getBasePermissionList(id)
      }
    })
  },
  getBasePermissionList(id) {
    app.axios('role', {
      op: 'ajaxBaseroleAll'
    }).then(res => {
      if (res.code) {
        res.lists.forEach(item => {
          item.checked = false
        })
        this.setData({
          basePermissionList: res.lists
        })
        if (id) {
          this.getPermissionInfo(id)
        } else {
          this.setData({
            permissionInfo: { content: res.lists }
          })
        }
      }
    })
  },
  getPermissionInfo(id) {
    app.axios('role', {
      op: 'ajaxRoleDetail',
      id: id
    }).then(res => {
      if (res.code) {
        const permissionInfo = res.item;
        // 处理 userids 为数组
        let userids = permissionInfo.userids || '';
        if (typeof userids === 'string') {
          userids = userids.split(',').map(userid => userid.trim());
        } else if (!Array.isArray(userids)) {
          userids = [];
        }
        let unames = permissionInfo.unames || '';
        let unameList = []
        if (typeof unames === 'string') {
          unameList = unames.split(',')
        } else if (!Array.isArray(unames)) {
          userids = [];
        } else {
          unameList = unames
        }
        permissionInfo.unameList = unameList
        console.log(permissionInfo)
        // 转换 userids 为 Set 以便快速查找
        const useridSet = new Set(userids);
        // 更新 userList 的 selected 状态
        const userList = this.data.userList.map(user => ({
          ...user,
          selected: useridSet.has(user.userid.toString()) // 根据实际情况调整类型转换
        }));
        // 设置数据
        this.setData({
          permissionInfo: permissionInfo,
          userList: userList
        });
      }
    });
  },
  navigateTo(e) {
    app.navigateTo(e.currentTarget.dataset.url, e.currentTarget.dataset.type)
  },
  toggleExpand() {
    this.setData({ expand: !this.data.expand })
  },
  togglePermissionSelector() {
    const picker = this.selectComponent('#list-picker')
    picker.togglePicker()
  },
  handleInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`permissionInfo.${field}`]: value
    })
  },
  submit() {
    const parmas = this.data.permissionInfo
    let op = 'ajaxRoleUp'
    let message = '修改成功'
    if (this.data.action === 'add') {
      op = 'ajaxRoleAdd'
      message = '添加成功'
    }
    parmas.op = op
    const checkData = []
    parmas.content.forEach(item => {
      if (item.checked) {
        checkData.push(item)
      }
    })
    parmas.checkData = checkData
    app.axios(
      'role',
      parmas
    ).then(res => {
      if (res.code) {
        wx.showToast({
          title: message
        })
        setTimeout(() => {
          app.navigateTo('/pages/operation-center/index/index?activeTab=5', 'redirectTo')
        }, 1500);
      }
    })
  },
  handleListConfirm(e) {
    const selectedItems = e.detail.selectedItems;
    // 提取所有userid和name生成字符串
    const userids = selectedItems.map(item => item.userid).join(',');
    const unames = selectedItems.map(item => item.name).join(',');
    const unamesList = selectedItems.map(item => item.name);
    // 更新权限组信息
    this.setData({
      'permissionInfo.userids': userids,
      'permissionInfo.unames': unames,
      'permissionInfo.unameList': unamesList,
    });

    // 同步更新userList选中状态（可选）
    const useridSet = new Set(selectedItems.map(item => item.userid.toString()));
    this.setData({
      userList: this.data.userList.map(user => ({
        ...user,
        selected: useridSet.has(user.userid.toString())
      }))
    });
  },
  handlePermissionCheck(e) {
    const zid = e.currentTarget.dataset.zid;
    // 获取当前权限内容数组
    const content = this.data.permissionInfo.content || [];
    // 创建新数组，更新对应zid的checked状态
    const newContent = content.map(item => {
      if (item.zid == zid) {
        return { ...item, checked: !item.checked };
      }
      return item;
    });
    // 更新data中的permissionInfo.content
    this.setData({
      'permissionInfo.content': newContent
    });
  }
})